package org.ytor.core.util;

import jakarta.annotation.Nonnull;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * created by yangtong on 2025/4/7 16:14:57
 */
@Component
public class SpringUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private static Environment environment;

    @Override
    public void setApplicationContext(@Nonnull ApplicationContext applicationContext) throws BeansException {
        SpringUtil.applicationContext = applicationContext;
        SpringUtil.environment = applicationContext.getEnvironment();
    }

    /**
     * 获取 Spring 上下文
     */
    public static ApplicationContext getApplicationContext() {
        check();
        return applicationContext;
    }

    /**
     * 根据 class 获取 Bean
     */
    public static <T> T getBean(Class<T> clazz) {
        check();
        return applicationContext.getBean(clazz);
    }

    /**
     * 根据 name 获取 Bean
     */
    public static Object getBean(String name) {
        check();
        return applicationContext.getBean(name);
    }

    /**
     * 根据 name 和 class 获取 Bean
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        check();
        return applicationContext.getBean(name, clazz);
    }

    /**
     * 根据class获取所有符合条件的bean
     */
    public static <T> List<T> getBeans(Class<T> clazz) {
        check();
        String[] names = applicationContext.getBeanNamesForType(clazz);

        return Arrays.stream(names).map(name -> applicationContext.getBean(name, clazz)).toList();
    }

    public static String getProperty(String key) {
        check();
        return environment.getProperty(key);
    }

    public static <T> T getProperty(String key, Class<T> clazz) {
        check();
        return environment.getProperty(key, clazz);
    }

    /**
     * 校验上下文是否注入
     */
    private static void check() {
        if (applicationContext == null) {
            throw new IllegalStateException("SpringContext未注入，请确保SpringUtil被Spring扫描！");
        }
        if (environment == null) {
            throw new IllegalStateException("environment未注入，请确保SpringUtil被Spring扫描！");
        }
    }
}
